package com.jmx.tomcat.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * 封装请求信息
 * @author: jmx
 * @date: 2023-08-11 17:47
 * @version: 1.0
 */
public class HttpRequest {
    //请求的方式，如 GET,POST
    private String method;
    //uri
    private String pattern;
    //请求携带的参数
    private HashMap<String,String> parameterMap;
    //从socket中获取输入流初始化数据
    private InputStream inputStream;

    public HttpRequest(InputStream inputStream) {
        this.inputStream = inputStream;
        parameterMap = new HashMap<>();
        initFields();
    }

    public HttpRequest() {
    }
    public String getParameter(String s){
        return parameterMap.get(s);
    }
    public String getMethod(){
        return this.method;
    }
    public String getPattern(){
        return this.pattern;
    }
    public void initFields() {
        //GET /server?n1=1&n2=2 HTTP/1.1
        try {
            BufferedReader bufferedReader =
                    new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String reqHead = bufferedReader.readLine();
            if(reqHead!=null&&!reqHead.isEmpty()){
                String[] element = reqHead.split(" ");
                method = element[0];
                String uri = element[1];
//                if(!uri.contains("?")){
//                    pattern = uri;
//                }
                String[] split = uri.split("\\?");
                pattern = split[0];
                if(split.length>1){
                    String[] params = split[1].split("&");
                    for (String param : params) {
                        String[] strs = param.split("=");
                        parameterMap.put(strs[0],strs[1]);
                    }
                }

            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
